package cn.tedu.superscholarstore.controller;


import cn.tedu.superscholarstore.mapper.UserMapper;
import cn.tedu.superscholarstore.pojo.dto.UserDTO;
import cn.tedu.superscholarstore.pojo.dto.UserLoginDTO;
import cn.tedu.superscholarstore.pojo.entity.User;
import cn.tedu.superscholarstore.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(@RequestBody UserDTO user) {
        UserVO userVO = mapper.selectByUsername(user.getUsername());
        User u = new User();
       BeanUtils.copyProperties(user,u);
        if (userVO != null) {
            return 2;}
        if (user.getPassword ().equals (user.getPasswordConfirm ()) ){
            mapper.insert(u);
            return 1;
        }
            return 3;

    }

    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDTO user,
                     HttpSession session, HttpServletResponse response) {
        UserVO userVO = mapper.selectByUsername(user.getUsername());
        if (userVO != null) {
            if (userVO.getPassword().equals(user.getPassword())) {
                session.setAttribute("user", userVO); // 存的键值对
                // 判断是否需要记住用户名和密码
                if (user.getRem()){
                    // 创建Cookie 对象,把用户名和密码装进Cookie;
                    Cookie c1 = new Cookie("username",user.getUsername());
                    // 设置保存时长,单位秒
                    c1.setMaxAge(60*60*24);
                    Cookie c2 = new Cookie("password",user.getPassword());
                    // 添加了响应对象
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                return 1;

            } else {
                return 3;
            }
        }
        return 2;
    }

    @RequestMapping("/getUser")
    public UserVO getUser(HttpSession session){
        return   (UserVO) session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }

}
